/**
 * DataSource React Query Hooks
 *
 * 数据源管理React Query钩子
 * - 使用TanStack Query进行服务器状态管理
 * - 自动缓存、重试、后台refetch
 * - 乐观更新
 */

import { useQuery, useMutation, useQueryClient, type UseQueryOptions } from '@tanstack/react-query'
import { message } from 'antd'
import { queryKeys, queryOptions } from '@/config/queryClient'
import {
  listDataSources,
  getDataSource,
  createDataSource,
  updateDataSource,
  deleteDataSource,
  testDataSourceConnection,
  enableDataSource,
  disableDataSource,
  batchEnableDataSources,
  batchDisableDataSources,
  batchDeleteDataSources,
} from '@/services/api/datasource'
import type {
  DataSource,
  DataSourceCreateRequest,
  DataSourceUpdateRequest,
  DataSourceTestRequest,
  DataSourceListParams,
  PageResponse,
} from '@/services/models/types'

/**
 * 获取数据源列表 (分页)
 */
export const useDataSourceList = (
  params: DataSourceListParams,
  options?: Omit<UseQueryOptions<PageResponse<DataSource>>, 'queryKey' | 'queryFn'>
) => {
  return useQuery({
    queryKey: queryKeys.datasources.list(params),
    queryFn: async () => {
      const response = await listDataSources(params)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    ...queryOptions.list,
    ...options,
  })
}

/**
 * 获取数据源详情
 */
export const useDataSource = (
  id: number,
  options?: Omit<UseQueryOptions<DataSource>, 'queryKey' | 'queryFn'>
) => {
  return useQuery({
    queryKey: queryKeys.datasources.detail(id),
    queryFn: async () => {
      const response = await getDataSource(id)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    ...queryOptions.detail,
    enabled: !!id,
    ...options,
  })
}

/**
 * 创建数据源
 */
export const useCreateDataSource = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (data: DataSourceCreateRequest) => {
      const response = await createDataSource(data)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    onSuccess: (data) => {
      // 使所有数据源列表查询失效
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      message.success(`数据源 "${data.name}" 创建成功`)
    },
    onError: (error: Error) => {
      message.error(`创建失败: ${error.message}`)
    },
  })
}

/**
 * 更新数据源
 */
export const useUpdateDataSource = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({ id, data }: { id: number; data: DataSourceUpdateRequest }) => {
      const response = await updateDataSource(id, data)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    onSuccess: (data, variables) => {
      // 使列表和详情查询失效
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(variables.id) })
      message.success(`数据源 "${data.name}" 更新成功`)
    },
    onError: (error: Error) => {
      message.error(`更新失败: ${error.message}`)
    },
  })
}

/**
 * 删除数据源 (软删除)
 */
export const useDeleteDataSource = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await deleteDataSource(id)
      if (!response.success) {
        throw new Error(response.message)
      }
      return id
    },
    onSuccess: (id) => {
      // 使列表和详情查询失效
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(id) })
      message.success('数据源删除成功')
    },
    onError: (error: Error) => {
      message.error(`删除失败: ${error.message}`)
    },
  })
}

/**
 * 测试数据源连接
 */
export const useTestDataSourceConnection = () => {
  return useMutation({
    mutationFn: async (data: DataSourceTestRequest) => {
      const response = await testDataSourceConnection(data)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    onSuccess: (data) => {
      if (data.success) {
        message.success(`连接成功! ${data.message || ''}`)
      } else {
        message.error(`连接失败: ${data.message}`)
      }
    },
    onError: (error: Error) => {
      message.error(`连接测试失败: ${error.message}`)
    },
  })
}

/**
 * 启用数据源
 */
export const useEnableDataSource = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await enableDataSource(id)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    onMutate: async (id) => {
      // 乐观更新 - 立即更新UI
      await queryClient.cancelQueries({ queryKey: queryKeys.datasources.detail(id) })
      const previousData = queryClient.getQueryData<DataSource>(queryKeys.datasources.detail(id))

      if (previousData) {
        queryClient.setQueryData<DataSource>(queryKeys.datasources.detail(id), {
          ...previousData,
          enabled: true,
        })
      }

      return { previousData }
    },
    onSuccess: (data, id) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(id) })
      message.success(`数据源 "${data.name}" 已启用`)
    },
    onError: (error: Error, id, context) => {
      // 回滚乐观更新
      if (context?.previousData) {
        queryClient.setQueryData(queryKeys.datasources.detail(id), context.previousData)
      }
      message.error(`启用失败: ${error.message}`)
    },
  })
}

/**
 * 禁用数据源
 */
export const useDisableDataSource = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await disableDataSource(id)
      if (!response.success) {
        throw new Error(response.message)
      }
      return response.data!
    },
    onMutate: async (id) => {
      // 乐观更新
      await queryClient.cancelQueries({ queryKey: queryKeys.datasources.detail(id) })
      const previousData = queryClient.getQueryData<DataSource>(queryKeys.datasources.detail(id))

      if (previousData) {
        queryClient.setQueryData<DataSource>(queryKeys.datasources.detail(id), {
          ...previousData,
          enabled: false,
        })
      }

      return { previousData }
    },
    onSuccess: (data, id) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(id) })
      message.success(`数据源 "${data.name}" 已禁用`)
    },
    onError: (error: Error, id, context) => {
      // 回滚乐观更新
      if (context?.previousData) {
        queryClient.setQueryData(queryKeys.datasources.detail(id), context.previousData)
      }
      message.error(`禁用失败: ${error.message}`)
    },
  })
}

/**
 * 批量启用数据源
 */
export const useBatchEnableDataSources = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (ids: number[]) => {
      const response = await batchEnableDataSources(ids)
      if (!response.success) {
        throw new Error(response.message)
      }
      return ids
    },
    onSuccess: (ids) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      ids.forEach((id) => {
        queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(id) })
      })
      message.success(`已启用 ${ids.length} 个数据源`)
    },
    onError: (error: Error) => {
      message.error(`批量启用失败: ${error.message}`)
    },
  })
}

/**
 * 批量禁用数据源
 */
export const useBatchDisableDataSources = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (ids: number[]) => {
      const response = await batchDisableDataSources(ids)
      if (!response.success) {
        throw new Error(response.message)
      }
      return ids
    },
    onSuccess: (ids) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      ids.forEach((id) => {
        queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(id) })
      })
      message.success(`已禁用 ${ids.length} 个数据源`)
    },
    onError: (error: Error) => {
      message.error(`批量禁用失败: ${error.message}`)
    },
  })
}

/**
 * 批量删除数据源
 */
export const useBatchDeleteDataSources = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (ids: number[]) => {
      const response = await batchDeleteDataSources(ids)
      if (!response.success) {
        throw new Error(response.message)
      }
      return ids
    },
    onSuccess: (ids) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.datasources.lists() })
      ids.forEach((id) => {
        queryClient.invalidateQueries({ queryKey: queryKeys.datasources.detail(id) })
      })
      message.success(`已删除 ${ids.length} 个数据源`)
    },
    onError: (error: Error) => {
      message.error(`批量删除失败: ${error.message}`)
    },
  })
}
